package controllers;

import helpers.CrawlerHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

public class CheckServerStatusServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		String name = (String) request.getParameter("domain");
		String httpStatus = null;
		String contentType = null;
		String loadtime = "";
		
		if (name != null && !UrlHelper.checkDomain(name)) {
			check.put("name", "Please input a valid domain.");
		} else if (name != null) {
			name = UrlHelper.getMainDomain(name);
		} 
		
		
		if (name != null && check.size() == 0) {
			
			String url = "";
			if (UrlHelper.checkIsSubDomain(name)) {
				url = "http://" + name;
			} else {
				url = "http://www." + name.replace("www.", "");
			}
			try {
				
				Long start = System.nanoTime();
				Connection conn = Jsoup.connect(url);
				int status = conn.followRedirects(true).execute().statusCode();
				
				Long end = System.nanoTime();
				long elapsedTime = end - start;
				double second = (double) elapsedTime / 1000000000.0;
				loadtime = Double.toString(second);
				
				if (status == 200 || status == 201 || status == 202 || status == 203 || status == 204 ) {
					httpStatus = "Online";
				} else {
					httpStatus = "Offline";
				}
				
				Document doc = conn
				.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
				.header("accept-Language", "en-us,en;q=0.5")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
				.followRedirects(true)
				.timeout(3000)
				.get();
				Response resp = conn.response();
				Map<String, String> headers = resp.headers();
				
				contentType = headers.get("content-type");
				
				System.out.println(loadtime);
				
			} catch (Exception e) {
				httpStatus = "Offline";
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		request.setAttribute("httpStatus", httpStatus);
		request.setAttribute("contentType", contentType);
		request.setAttribute("loadtime", loadtime);
		try {
			request.getRequestDispatcher("/pages/check_server_status.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
	}
}
